package com.haojiang.mh.ui.activity

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.haojiang.mh.R
import com.haojiang.mh.ui.base.BaseActivity
import com.haojiang.mh.utils.SpUtil
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_permission.*
import android.os.Bundle

import android.content.pm.PackageManager;
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat


/**
 * 权限申请页
 *
 * Created by ZapFive on 2019-05-25.
 *
 * wuzhuang@mirahome.me
 */
class PermissionActivity : BaseActivity() {

    private val phoneGroup = arrayOf(Manifest.permission.READ_PHONE_STATE)
    private val permissionLocationTexts = intArrayOf(
            R.string.permission_location_info,
            R.string.permission_location_granted,
            R.string.permission_location_not_granted
    )
    private val permissionStorageTexts = intArrayOf(
            R.string.permission_storage_info,
            R.string.permission_storage_granted,
            R.string.permission_storage_not_granted
    )
    private val permissionPhoneTexts = intArrayOf(
            R.string.permission_phone_info,
            R.string.permission_phone_granted,
            R.string.permission_phone_not_granted
    )
    val REQUEST_READ_PHONE_STATE = 10000
    override fun beforeSetContentView() {
        isNeedWiFiOrBluetoothTip = false
    }

    override fun getLayoutId() = R.layout.activity_permission

    override fun getTitleName(): String? = null

    override fun initActivity() {
    }

    override fun initView() {
        ab_location.setOnClickListener {
            requestSingle(0, permissionLocationTexts)
        }
        ab_storage.setOnClickListener {
            requestSingle(1, permissionStorageTexts)
        }
        ab_phone.setOnClickListener {
            requestSingle(2, permissionPhoneTexts)
        }
        ab_next.setOnClickListener {
            when {
                !aiv_tick_location.isShown -> {
                    requestSingle(0, permissionLocationTexts)
                    return@setOnClickListener
                }
                !aiv_tick_storage.isShown -> {
                    requestSingle(1, permissionStorageTexts)
                    return@setOnClickListener
                }
                !aiv_tick_phone.isShown -> {
                    requestSingle(2, permissionPhoneTexts)
                    return@setOnClickListener
                }
            }
            if (isFirstLauncher()) {
                redirectNoParamAndFinish(ChooseWebServiceActivity::class.java)
            } else {
                redirectNoParamAndFinish(MainActivity::class.java)
            }
        }
    }

    /**
     * 单个申请
     */
    private fun requestSingle(type: Int, txtArr: IntArray) {
        val tv: TextView
        val img: View
        val btn: View
        val permission: Array<String>
        val spType: String
        when (type) {
            0 -> {
                permission = Permission.Group.LOCATION
                tv = tv_location_content
                img = aiv_tick_location
                btn = ab_location
                spType = "permission_location"
            }
            1 -> {
                permission = Permission.Group.STORAGE
                tv = tv_storage_content
                img = aiv_tick_storage
                btn = ab_storage
                spType = "permission_storage"
            }
            2 -> {
                permission = phoneGroup
                tv = tv_phone_content
                img = aiv_tick_phone
                btn = ab_phone
                spType = "permission_phone"
                Log.v("---------------phone","${permission}")

            }
            else -> return
        }
        Log.v("---------------spType","${SpUtil[spType, true]}")
        if (!SpUtil[spType, true]) {
            turnSetting()
        } else {
            if (type < 2){
                AndPermission.with(context)
                    .runtime()
                    .permission(permission)
                    .onGranted {
                        SpUtil.put(spType, true)
                        refreshView(1, txtArr[1], tv, img, btn)
                        Log.v("---------------权限状态：","同意")
                    }
                    .onDenied {
                        SpUtil.put(spType, false)
                        showToast(R.string.tip_open_location_permission)
                        refreshView(2, txtArr[2], tv, img, btn)
                        Log.v("---------------权限状态：","拒绝")
                    }
                    .start()
            }else{
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.READ_PHONE_STATE), REQUEST_READ_PHONE_STATE)
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {

        when (requestCode) {
            REQUEST_READ_PHONE_STATE -> if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //TODO
                SpUtil.put("permission_phone", true)
                refreshView(1, permissionPhoneTexts[1], tv_phone_content, aiv_tick_phone, ab_phone)
                Log.v("+++++++++++++权限状态：","同意")

            } else {
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) {
                    Log.e("-------", "拒绝权限并且勾选了不再提示: ")

                }
                SpUtil.put("permission_phone", false)
                showToast(R.string.tip_open_location_permission)
                refreshView(2, permissionPhoneTexts[2], tv_phone_content, aiv_tick_phone, ab_phone)
                Log.v("+++++++++++++++++权限状态：","拒绝")
            }
            else -> {
            }
        }
    }

    /**
     * 跳转应用详情页
     */
    private fun turnSetting() {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.fromParts("package", context.packageName, null)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        context.startActivityForResult(intent, 0x1111)
    }

    /**
     * 刷新
     */
    private fun refreshView(state: Int, rsId: Int, tv: TextView, img: View, btn: View) {
        tv.text = getString(rsId)
        val parent = tv.parent as ViewGroup
        var showTick = false
        when (state) {
            0 -> {
                parent.setBackgroundResource(R.drawable.shape_gray_card)
                btn.visibility = View.VISIBLE
                img.visibility = View.GONE
            }
            1 -> {
                parent.setBackgroundResource(R.drawable.shape_green_card)
                showTick = true
            }
            2 -> {
                parent.setBackgroundResource(R.drawable.shape_yellow_card)
            }
        }
        img.visibility = if (showTick) View.VISIBLE else View.GONE
        btn.visibility = if (showTick) View.INVISIBLE else View.VISIBLE
        btn.isClickable = !showTick
    }

    /**
     * 版本大于23
     */
    fun isMarshmallow(): Boolean {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

//        RequestPhoneStatePermission()
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onResume() {
        super.onResume()

        val result0 = AndPermission.hasPermissions(context, *Permission.Group.LOCATION)
        val state0 = if (result0) 1 else if (SpUtil["permission_location", true]) 0 else 2
        resumeView(state0, 0, permissionLocationTexts)

        val result1 = AndPermission.hasPermissions(context, *Permission.Group.STORAGE)
        val state1 = if (result1) 1 else if (SpUtil["permission_storage", true]) 0 else 2
        resumeView(state1, 1, permissionStorageTexts)

//        val result2 = AndPermission.hasPermissions(context, *phoneGroup)


        val result3 = ContextCompat.checkSelfPermission(context,Manifest.permission.READ_PHONE_STATE)
        if (result3 != PackageManager.PERMISSION_GRANTED) {
            Log.v("---------------check","granted")

        }else{
            Log.v("-------++++++++check","-------")
        }
        val state2 = if (result3 == 0) 1 else if (SpUtil["permission_phone", true]) 0 else 2
        Log.v("---------------state2","${state2}")
        resumeView(state2, 2, permissionPhoneTexts)


    }
    /**
     * resume刷新View
     */
    private fun resumeView(state: Int, type: Int, txtArr: IntArray) {
        val tv: TextView
        val img: View
        val btn: View
        when (type) {
            0 -> {
                tv = tv_location_content
                img = aiv_tick_location
                btn = ab_location
            }
            1 -> {
                tv = tv_storage_content
                img = aiv_tick_storage
                btn = ab_storage
            }
            2 -> {
                tv = tv_phone_content
                img = aiv_tick_phone
                btn = ab_phone
            }
            else -> return
        }
        refreshView(state, txtArr[state], tv, img, btn)
    }
}
